package clients

import (
	"errors"
	"strconv"
	"sync"

	"gitee.com/sansaniot/ssiot-core/logger"
	mqtt "github.com/eclipse/paho.mqtt.golang"

	"ssforward/common/constant"
	"ssforward/common/enums"
	mq "ssforward/common/middleware/mqtt"
	"ssforward/common/utils"
	"ssforward/internal/forward/models"
)

var ForwardMqClients sync.Map

func InitMqClientList(serverList []models.SysForwardServer) {
	for i := range serverList {
		go func(serverItem models.SysForwardServer) {
			_ = InitMqClientItem(serverItem)
		}(serverList[i])
	}
}

func InitMqClientItem(serverItem models.SysForwardServer) error {
	clientPoint, err := instanceServerMqClient(serverItem)
	if err != nil {
		logger.Errorf("[%+v],当前mq转发服务配置信息=[%+v]", err.Error(), serverItem)
		return err
	}
	//缓存当前客户端对象
	ForwardMqClients.Store(clientPoint.ClientId, clientPoint)
	return nil
}

// 删除客户端对象
func RemoveMqClientItem(clientId string) {
	if item, ok := ForwardMqClients.Load(clientId); ok && item != nil {
		clientItem := item.(*mq.Client)
		//断开原始连接
		clientItem.DisConnect()
		//移除缓存
		ForwardMqClients.Delete(clientId)
		logger.Infof("断开转发mq连接,并删除缓存 clientId=[%+v]", clientId)
	}
}

func instanceServerMqClient(serverItem models.SysForwardServer) (*mq.Client, error) {
	serverMqClient := &mq.Client{
		ClientId: enums.Mqtt.Get().Value + constant.MqttNumber + "-" + serverItem.Id,
		Timeout:  10,
	}
	if len(serverItem.Host) > 0 {
		serverMqClient.Broker = serverItem.Host
	}
	if serverItem.Port > 0 {
		serverMqClient.Port = strconv.Itoa(serverItem.Port)
	}
	if len(serverItem.Username) > 0 {
		serverMqClient.Username = serverItem.Username
	}
	if len(serverItem.Password) > 0 {
		var err any
		serverMqClient.Password, err = utils.AesDecrypt(serverItem.Password, constant.SALTKEY)
		if err != nil {
			return nil, errors.New("解密mq密码失败")
		}
	}
	serverMqClient.Handlers = make(map[string]mqtt.MessageHandler)
	if _, err := serverMqClient.CreateClient(); err != nil {
		logger.Error("转发mq客户端创建失败" + err.Error())
		return nil, errors.New("mq客户端创建失败: " + err.Error())
	}
	return serverMqClient, nil
}

// 测试连接
func TestMqttClientItem(serverItem models.SysForwardServer) (err error) {
	clientId := enums.Mqtt.Get().Value + constant.MqttNumber + "-" + serverItem.Id
	if item, ok := ForwardMqClients.Load(clientId); ok && item != nil {
		clientItem := item.(*mq.Client)
		if !clientItem.IsConnected() {
			err = errors.New("连接异常断开")
		}
	} else {
		err = InitMqClientItem(serverItem)
	}
	return
}
